class Solution {
public:
    int maxSubarraySumCircular(vector<int>& nums) {
        int n = nums.size();
        vector<int> f(n), g(n);;
        int fmax = f[0] = g[0] = nums[0], sum = nums[0], gmin = nums[0];
        for(int i = 1; i < n; ++i)
        {
            sum += nums[i];
 
            f[i] = max(nums[i], f[i-1] + nums[i]);
            fmax = max(fmax, f[i]);
 
            g[i] = min(nums[i], g[i-1] + nums[i]);
            gmin = min(gmin, g[i]);
        }
        return sum == gmin ? fmax : max(fmax, sum - gmin);
    }
};